//
//  SettingTableViewController.swift
//  ddx0513
//
//  Created by ejian  on 15/6/2.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

class SettingTableViewController: UITableViewController, UIGestureRecognizerDelegate, PopupDelegate {
    var interval = 0
    var oneMonthPrice = 0.0
    var sixMonthsPrice = 0.0
    var oneYearPrice = 0.0

    @IBOutlet weak var nickLabel: UILabel!
    @IBOutlet weak var accountLabel: UILabel!
    @IBOutlet weak var sixMonthOldPriceLabel: UILabel!
    @IBOutlet weak var oneYearOldPriceLabel: UILabel!
    @IBOutlet weak var vipTimeLabel: UILabel!
    @IBOutlet weak var vipLeftTimeLabel: UILabel!
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var cacheSizeLabel: UILabel!
    @IBOutlet weak var wifiNetButton: UIButton!
    @IBOutlet weak var oneMonthLabel: UILabel!
    @IBOutlet weak var sixMonthsLabel: UILabel!
    @IBOutlet weak var oneYearLabel: UILabel!
    @IBOutlet weak var operaterLabel: UILabel!
    
    // MARK: - 函数
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        //显示导航栏
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        
        self.accountLabel.text = "登录账户：\(DBUtils.mem.loginName)"
        
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLBase(), parameters: nil, responseHandler: nil, netErrorHandler: nil, successHandler: initPrice, interErrorHandler: nil, jsonErrorHandler: nil)
        
        self.cacheSizeLabel.text = "计算中.."
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            let cacheSize = FileUtils.calcFoldSize()
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.cacheSizeLabel.text = StringUtils.formatFileSize(cacheSize)
            })
        })
        
        if (!DBUtils.mem.isCellularNet) {
            wifiNetButton.setBackgroundImage(UIImage(named: "设置-未开启_03"), forState: UIControlState.Normal)
        } else {
            wifiNetButton.setBackgroundImage(UIImage(named: "设置_13"), forState: UIControlState.Normal)
        }
        
        self.useBlurForPopup = false
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("weixinPayHandler:"), name: StringUtils.WeipayNotification, object: nil)
        self.tableView.tableFooterView = UIView(frame: CGRectZero)
    }
    
    
    
    override func viewWillAppear(animated: Bool) {
        if (DBUtils.mem.nickName == "") {
            self.nickLabel.text = "未设置"
        } else {
            self.nickLabel.text = DBUtils.mem.nickName
        }
        
        if (DBUtils.mem.imgURL != "") {
            DBUtils.getImageFromFile(DBUtils.mem.imgURL, successHandler: { (_imageURL, _image) -> Void in
                if (_imageURL == DBUtils.mem.imgURL) {
                    self.userImageView.image = _image
                }
            })
        }
    }
    
    override func viewDidDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: StringUtils.WeipayNotification, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func weixinPayHandler(notification: NSNotification) {
        self.dismissPopupViewControllerAnimated(false, completion: nil)
        let resp = notification.object as! BaseResp
        
        switch(resp.errCode) {
        case 0:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付成功")
            
            let a = ["mobile": DBUtils.mem.loginName, "pwd": DBUtils.mem.password]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLLogin(), parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: login, interErrorHandler: nil, jsonErrorHandler: nil)
        case -2:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "用户点击取消并返回")
        default:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付失败")
            
        }
    }
    
    @IBAction func backButtonPressed(sender: AnyObject) {
        self.navigationController?.popViewControllerAnimated(true)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }

    //退出登录
    @IBAction func logoutButtonPressed(sender: AnyObject) {
        var userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(false, forKey: DBUtils.varNames.loginStatus)
        userDefault.synchronize()
        
        DBUtils.mem.loginStatus = false
        rootController.navigationController?.popToRootViewControllerAnimated(true)
        rootController.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    //一个月VIP
    @IBAction func oneMonthVipButtonPressed(sender: AnyObject) {
        if (DBUtils.mem.vipType == "NOTIME_VIP") {
            ViewUtils.popMessage(self, title: "订购失败", message: "您已开通VIP会员，无需重复开通。")
        } else {
            var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayChannel") as! PayChannelViewController
            viewController.delegate = self
            viewController.aliPay = self.oneMonthPrice
            viewController.weixinPay = self.oneMonthPrice
            viewController.month = 1
            self.presentPopupViewController(viewController, animated: true, completion: nil)
            self.setPopviewGuesture()
        }
    }
    
    //六个月VIP
    @IBAction func sixMonthVipButtonPressed(sender: AnyObject) {
        if (DBUtils.mem.vipType == "NOTIME_VIP") {
            ViewUtils.popMessage(self, title: "订购失败", message: "您已开通VIP会员，无需重复开通。")
        } else {
            var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayChannel") as! PayChannelViewController
            viewController.delegate = self
            viewController.aliPay = self.sixMonthsPrice
            viewController.weixinPay = self.sixMonthsPrice
            viewController.month = 6
            self.presentPopupViewController(viewController, animated: true, completion: nil)
            self.setPopviewGuesture()
        }
    }
    
    //一年VIP
    @IBAction func oneYearVipButtonPressed(sender: AnyObject) {
        if (DBUtils.mem.vipType == "NOTIME_VIP") {
            ViewUtils.popMessage(self, title: "订购失败", message: " 您已开通VIP会员，无需重复开通。")
        } else {
            var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayChannel") as! PayChannelViewController
            viewController.delegate = self
            viewController.aliPay = self.oneYearPrice
            viewController.weixinPay = self.oneYearPrice
            viewController.month = 12
            self.presentPopupViewController(viewController, animated: true, completion: nil)
            self.setPopviewGuesture()
        }

    }
    
    //手机开通
    @IBAction func phoneVipButtonPressed(sender: AnyObject) {
        if (DBUtils.mem.vipType == "NOTIME_VIP") {
            ViewUtils.popMessage(self, title: "订购失败", message: "您已开通VIP会员，无需重复开通。")
        } else if (DBUtils.mem.vipType == "TIME_VIP") {
            ViewUtils.popMessage(self, title: "订购失败", message: " 服务未到期，请在\(self.interval)天后订购开通。")
        } else {
            var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("PayCenter") as! PayCenterViewController
            viewController.delegate = self
            self.presentPopupViewController(viewController, animated: true, completion: nil)
            self.setPopviewGuesture()
        }
    }
    
    @IBAction func netSwitchPressed(sender: AnyObject) {
        DBUtils.mem.isCellularNet = !DBUtils.mem.isCellularNet
        var userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(DBUtils.mem.isCellularNet, forKey: DBUtils.varNames.isCellularNet)
        userDefault.synchronize()
        
        if (!DBUtils.mem.isCellularNet) {
            wifiNetButton.setBackgroundImage(UIImage(named: "设置-未开启_03"), forState: UIControlState.Normal)
        } else {
            wifiNetButton.setBackgroundImage(UIImage(named: "设置_13"), forState: UIControlState.Normal)
        }
        
    }
    
    func setPopviewGuesture() {
        var fadeview = self.getBlueView()
        var tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismissPopup:"))
        tapRecognizer.numberOfTapsRequired = 1
        tapRecognizer.delegate = self
        fadeview.addGestureRecognizer(tapRecognizer)
    }
    
    func setProgress(cell: UITableViewCell) {
        let x = 15 as CGFloat, y = 37 as CGFloat
        
        let width = cell.frame.width - 30
        let imgb = UIImage(named: "进度条2b.png")
        var imgbView = UIImageView(image: imgb)
        imgbView.frame = CGRectMake(x, y, width, imgb!.size.height)
        cell.addSubview(imgbView)
        
        if (DBUtils.mem.vipType == "TIME_VIP") {
            let timePassed = StringUtils.getDayCount(Double(DBUtils.mem.vipBegin), toTime: NSDate().timeIntervalSince1970 * 1000)
            let allTime = StringUtils.getDayCount(Double(DBUtils.mem.vipBegin), toTime: Double(DBUtils.mem.vipExpire))
            var jd = CGFloat(timePassed) / CGFloat(allTime)
            
            let upWidth = width * jd
            var img1 = UIImage(named: "进度条2.png")
            var img = UIImageView(image: img1)
            if (upWidth < img1!.size.width) {
                img.clipsToBounds = true
                img.contentMode = UIViewContentMode.Left
            } else {
                jd = 1.0 as CGFloat
            }
            img.frame = CGRectMake(x, y, upWidth, img1!.size.height)
            cell.addSubview(img)
            
            let img32 = UIImage(named: "进度条圆点.png")
            var img3 = UIImageView(image: img32)
            img3.frame = CGRectMake(x + upWidth - img32!.size.width / 2, y + img1!.size.height / 2 - img32!.size.height / 2, img32!.size.width, img32!.size.height)

            var color = img1?.colorAtPixel(CGPoint(x: img1!.size.width * jd - 1, y: img1!.size.height / 2))
            var img3b2 = UIImage(named: "进度条圆点背景.png")!.imageWithGradientTintColor(color)
            var img3b = UIImageView(image: img3b2)
            let dis = 3 as CGFloat
            var xx: CGFloat?, yy: CGFloat?
            xx = x + upWidth + img32!.size.width / 2 + dis - img3b2!.size.width
            yy = y + img1!.size.height / 2 - img3b2!.size.height / 2
            if (xx < x) {
                xx = x
                img3b.image = img3b2!.imageWithGradientTintColor(UIColor(red: 241/255, green: 215/255, blue: 79/255, alpha: 1.0))
                img3.frame = CGRectMake(x + img3b2!.size.width - img32!.size.width - dis, y + img1!.size.height / 2 - img32!.size.height / 2, img32!.size.width, img32!.size.height)
            }
            let a = xx! + img3b2!.size.width
            let b = x + width + img32!.size.width / 2 + dis
            if (a > b) {
                xx = b - img3b2!.size.width
            }
            img3b.frame = CGRectMake(xx!, yy!, img3b2!.size.width, img3b2!.size.height)
            cell.addSubview(img3b)

            cell.addSubview(img3)
        }
    }
    
    func setVipInfo(cell: UITableViewCell) {
        if (DBUtils.mem.vipType == "NONE_VIP") {
            self.vipTimeLabel.text = "VIP到期时间：非会员"
            self.vipLeftTimeLabel.text = ""
        } else if (DBUtils.mem.vipType == "TIME_VIP") {
            self.vipTimeLabel.text = "VIP到期时间：" + StringUtils.getDateString(Double(DBUtils.mem.vipExpire), format: "yyyy-MM-dd")
            self.interval = StringUtils.getDayCount(NSDate().timeIntervalSince1970 * 1000, toTime: Double(DBUtils.mem.vipExpire))
            self.vipLeftTimeLabel.text = "还剩\(self.interval)天"
            setProgress(cell)
        } else if (DBUtils.mem.vipType == "NOTIME_VIP") {
            self.vipTimeLabel.text = "VIP到期时间：包月"
            self.vipLeftTimeLabel.text = ""
            setProgress(cell)
        }
    }
    
    func setPrice(priceOri: Int, price: Int, cell: UITableViewCell, frame: CGRect) {
        if (priceOri == price) {
            var label = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 32, 18))
            label.text = "￥\(priceOri / 100)"
            let font = UIFont.systemFontOfSize(15 as CGFloat)
            label.font = font
            label.textColor = UIColor.orangeColor()
            let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))
            cell?.addSubview(label)
        } else {
            var label1 = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 43, 17))
            label1.text = "￥\(priceOri / 100)"
            let font1 = UIFont.systemFontOfSize(14 as CGFloat)
            label1.font = font1
            label1.textColor = UIColor.lightGrayColor()
            cell.addSubview(label1)
            
            var str = label1.text
            var num = count(str!)
            let attr = NSMutableAttributedString(string: str!)
            attr.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(integer: 1), range: NSMakeRange(0, num))
            label1.attributedText = attr
            label1.sizeToFit()
            
            let frame2 = label1.frame
            var label2 = UILabel(frame: CGRectMake(frame2.origin.x + frame2.size.width, frame2.origin.y, 104, 21))
            label2.text = "立享优惠￥\(price / 100)"
            let font2 = UIFont.systemFontOfSize(13 as CGFloat)
            label2.font = font2
            label2.textColor = UIColor.redColor()
            cell.addSubview(label2)
        }
    }
    
    //MARK: - 网络回调函数
    
    func initPrice(data: JSON) {
        var title = data["title"].string
        var eversion = data["eversion"].string
        var showEversion = data["show_eversion"].string
        var customerPhone = data["customer_phone"].string
        var operaterAmt = data["operater_amt"].int
        var monthAmt1Ori = data["month_amt_1_ori"].int
        var monthAmt1 = data["month_amt_1"].int
        var monthAmt6Ori = data["month_amt_6_ori"].int
        var monthAmt6 = data["month_amt_6"].int
        var monthAmt12Ori = data["month_amt_12_ori"].int
        var monthAmt12 = data["month_amt_12"].int
        
        self.oneMonthPrice = Double(monthAmt1!) / 100.0
        self.sixMonthsPrice = Double(monthAmt6!) / 100.0
        self.oneYearPrice = Double(monthAmt12!) / 100.0
        
        self.setPrice(monthAmt1Ori!, price: monthAmt1!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))!, frame: self.oneMonthLabel.frame)
        self.setPrice(monthAmt6Ori!, price: monthAmt6!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 1))!, frame: self.sixMonthsLabel.frame)
        self.setPrice(monthAmt12Ori!, price: monthAmt12!, cell: self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 1))!, frame: self.oneYearLabel.frame)
        
        let frame = self.operaterLabel.frame
        var label = UILabel(frame: CGRectMake(frame.origin.x + frame.size.width + 5, frame.origin.y, 53, 18))
        label.text = "￥\(operaterAmt! / 100)/月"
        let font = UIFont.systemFontOfSize(15 as CGFloat)
        label.font = font
        label.textColor = UIColor.orangeColor()
        let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 1))
        cell?.addSubview(label)
    }
    
    func login(json: JSON) {
        var userId = json["userid"].int
        var nickName = json["nickname"].string
        var imgUrl = json["imgurl"].string
        var pushAlias = json["push_alias"].string
        var pushTag = json["push_tag"].string
        var imUsername = json["im_username"].string
        var imPassword = json["im_password"].string
        var vipType = json["vip_type"].string
        var vipBegin = json["vip_begin"].int64
        var vipExpire = json["vip_expire"].int64
        var token = json["token"].string
        
        DBUtils.mem.loginStatus = true
        if let a = userId {
            DBUtils.mem.userId = a
        }
        if let a = nickName {
            DBUtils.mem.nickName = a
        }
        if let a = imgUrl {
            DBUtils.mem.imgURL = a
        }
        if let a = pushAlias {
            DBUtils.mem.pushAlias = a
        }
        if let a = pushTag {
            DBUtils.mem.pushTag = a
        }
        if let a = imUsername {
            DBUtils.mem.imUsername = a
        }
        if let a = imPassword {
            DBUtils.mem.imPassword = a
        }
        if let a = token {
            DBUtils.mem.token = a
        }
        if let a = vipType {
            DBUtils.mem.vipType = a
        }
        if let a = vipBegin {
            DBUtils.mem.vipBegin = a
        }
        if let a = vipExpire {
            DBUtils.mem.vipExpire = a
        }
        
        setVipInfo(tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))!)
    }
    
    // MARK: - PopupDelegate
    
    func dismissPopup(animated: Bool) ->Void {
        if (self.popupViewController != nil) {
            self.dismissPopupViewControllerAnimated(animated, completion: nil)
        }
    }
    
    func payResult(channel: String, resultStatus: String) {
        self.dismissPopupViewControllerAnimated(false, completion: nil)
        
        if (resultStatus == "9000" || resultStatus == "8000") {
            let a = ["mobile": DBUtils.mem.loginName, "pwd": DBUtils.mem.password]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLLogin(), parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: login, interErrorHandler: nil, jsonErrorHandler: nil)
        }
        
        if (channel == StringUtils.payChannel["alipay"]) {
            ViewUtils.popMessage(self, title: "支付宝支付结果", message: StringUtils.alipayErrorCode[resultStatus]!)
        }
    }
    
    // MARK: - Table view data source
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if (indexPath.section == 0 && indexPath.row == 1) {
            setVipInfo(cell)
        }
    }
    
    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch (section) {
        case 1:
            return 30
        case 2, 3, 4:
            return 10
        default:
            return 0
        }
    }
    
    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var r = UIScreen.mainScreen().bounds
        
        var fontSize: CGFloat = 13.0
        if (r.width <= 320) {
            fontSize = 11.0
        }
        
        switch (section) {
        case 1:
            var label = UILabel(frame: CGRect(x: 20, y: 0, width: r.width - 20, height: 30))
            
            label.font = label.font.fontWithSize(fontSize)
            label.text = "开通VIP会员，免费观看全部视频—在线支付"
            
            var sectionView = UIView(frame: CGRect(x: 0, y: 0, width: r.width, height: 30))
            sectionView.backgroundColor = UIColor.groupTableViewBackgroundColor()
            sectionView.addSubview(label)
            
            return sectionView
        default:
            return nil
        }
    }
    
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if (indexPath.section == 0 && indexPath.row == 0) { //头像
            var storyBoard = UIStoryboard(name: "Setting", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("AccountSetting") as! AccountSettingViewController
            
            self.navigationController?.pushViewController(viewController, animated: true)
        } else if (indexPath.section == 2 && indexPath.row == 0) { //清除缓存
            self.cacheSizeLabel.text = "清除中.."
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
                FileUtils.removeFiles()
                let cacheSize = FileUtils.calcFoldSize()
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.cacheSizeLabel.text = StringUtils.formatFileSize(cacheSize)
                })
            })
        } else if (indexPath.section == 3 && indexPath.row == 0) { //意见反馈
            var storyBoard = UIStoryboard(name: "Setting", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("Feedback") as! FeedbackViewController
            self.navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
//    override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        var view = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 20))
//        view.backgroundColor = UIColor.clearColor()
//        return view
//    }
//    
//    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        return 0
//    }
    
    
    
//    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCellWithIdentifier("timeCell", forIndexPath: indexPath) as! UITableViewCell
//
//        
//
//        return cell
//    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
